<html> 
<head> 
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> 
<script src="http://code.jquery.com/jquery-latest.min.js"></script> 
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script> 
 
<script type="text/javascript"> 
 
    /* Config params */
    var use_map = 1;
    var use_location = 1;
 
    /* Internal vars */
    var image = 'ghost.png';
    var playersArray = [];
    var applesArray = [];
    var map = '';
    var lat_center = 32.064774;
    var lng_center = 34.775655;
    var errors = 0;
    var init_done = 0;
 
    /* For testing only */
    var lat_fake = 40.714;
    var lng_fake = -74.005;
    var lat_dir_fake = -1 + 2 * Math.floor(Math.random()*2);
    var lng_dir_fake = -1 + 2 * Math.floor(Math.random()*2);
 
    function dbg_print(str) {
        $('#dbg').prepend('<p>' + str + '</p>');
        console.log(str);
    }
 
    function user_print(str) {
        $('#info').html('<h2>'+ str + '</h2>');
        //dbg_print('USER: ' + str);
    }
 
    if (use_map) {
    var pacman_image = new google.maps.MarkerImage('http://pacman.itlater.com/static/static/pacman.png',
      new google.maps.Size(14, 14),
      new google.maps.Point(0,0),
      new google.maps.Point(7, 7));
 
    var ghost_image = new google.maps.MarkerImage('http://pacman.itlater.com/static/static/ghost.png',
      new google.maps.Size(14, 14),
      new google.maps.Point(0,0),
      new google.maps.Point(7, 7));
 
    var apple_image = new google.maps.MarkerImage('http://pacman.itlater.com/static/static/apple.png',
      new google.maps.Size(10, 10),
      new google.maps.Point(0,0),
      new google.maps.Point(5, 5));
    }
 
    var Apple = function apple(lat, lng, id) {
        this.lat = lat;
        this.lng = lng;
        this.id = id;
 
        //dbg_print('New apple ' + lat + ':' + lng);
 
        if (use_map) {
            var latlng = new google.maps.LatLng(this.lat, this.lng);
 
            this.marker = new google.maps.Marker({
                position: latlng,
                title: 'Apple',
                icon: apple_image,
                map: map
            });
        }
 
        this.remove = function() {
            //dbg_print('Remove apple #' + this.id);
            if (use_map)
                this.marker.setMap();
        };
        
        applesArray.push(this);
    }
 
    var Player = function player(lat, lng, type, id) {
        this.lat = lat;
        this.lng = lng;
        this.type = type;
        this.id = id;
        
        //dbg_print('Player ' + id + '  ' + lat + ':' + lng);
 
        if (use_map) {
        var latlng = new google.maps.LatLng(this.lat, this.lng);
 
        this.marker = new google.maps.Marker({
            position: latlng,
            title: 'Sample',
            icon: type == 1 ? pacman_image : ghost_image,
            map: map
        });
        }
 
        this.remove = function() {
            //dbg_print('Remove player ' + this.id);
            if (use_map)
                this.marker.setMap();
        };
        
        playersArray.push(this);
    }    
 
    function fake_coordiates(callback) {
        lat_fake = lat_fake + 0.0001 * lat_dir_fake;
        lng_fake = lng_fake + 0.0001 * lng_dir_fake;
 
        if (lat_fake > (lat_center + 0.003) || lat_fake < (lat_center - 0.003))
            lat_dir_fake *= -1;
 
        if (lng_fake > (lng_center + 0.003) || lng_fake < (lng_center - 0.003))
            lng_dir_fake *= -1;
 
        callback(lat_fake, lng_fake);
    }
 
    function get_location(callback) {
        if (!use_location)
        {
            fake_coordiates(callback);
            return;
        }
 
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                    callback(position.coords.latitude, position.coords.longitude);
                    }, function(position_error) {
                    /* Error getting location */
                    errors += 1;
                    user_print('Error getting location (' + position_error.message + ')');
                    }, {
                enableHighAccuracy: true
             });
        } else {
            user_print('The W3C Geolocation API isn\'t supported');
        }    
    }
 
    function update_state(data) {
        //dbg_print('Got state update !');
 
        /* Display all players */
        if (data.players) 
        {
            //dbg_print('Remove old players');
 
            /* Remove previous map entities */
            while (playersArray.length) {
                player = playersArray.pop();
                player.remove()
            }
 
            //dbg_print('Load up new players');
 
            $.each(data.players, function(i,item) { 
                    var player = new Player(item.lat, item.lng, item.role, item.id)
            });
        }
 
        $.each(data.orders, function(i,item) { 
 
            //dbg_print('Handle command: ' + item.order);
 
            switch (item.order) 
            {
            case 'RemoveApple':
                for (i in applesArray)
                    if (applesArray[i].id == item.id) {
                        applesArray[i].remove();
                        applesArray.splice(i, 1);
                    }
                break;
 
            default:
                //dbg_print('Unknown command: ' + item.order);
            };
        });
 
        $.each(data.messages, function(i,item) { 
            user_print(item.msg);
        });
 
    }
   
    function update_position(lat, lng) {
        if (errors > 5) {
            //dbg_print('Too many errors...');
            return;
        }
 
        dbg_print('Got updated position ' + lat + ':' + lng);
        $.getJSON("data/update.js", { lat:lat, lng:lng, }, update_state);
    }
 
    function game_update() {
        if (errors > 5) {
            dbg_print('Too many errors...');
            return;
        }
 
        dbg_print('Starting update sequence');
        get_location(update_position);
 
        setTimeout(game_update, 1000 * 1);
    };
 
    function init_map() {
        var latlng = new google.maps.LatLng(lat_center, lng_center);
    
        var myOptions = {
          zoom: 14,
          center: latlng,
          mapTypeId: google.maps.MapTypeId.SATELLITE /* ROADMAP - From some reason doesnt show roads in Israel */
        };
 
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    
        /* Creating biding area circle */
        var circle = new google.maps.Circle({
            center: latlng,
            fillColor: "#008800",
            fillOpacity: 0.2,
            map: map,
            radius: 500,
            strokeColor: "#ff0000",
            strokeOpacity: 0.9,
            strokeWeight: 5,
            zIndex: 10
        });
    }
 
    function init_game(data)
    {
        /* Verify we run this once */
        if (init_done) return; else init_done = 1;
            
        if (data == null)
        {
            dbg_print('Game init passed no data');
            return;
        }
 
        dbg_print('Got initial json data, start init.. ');
 
        if (use_map)
            init_map();
 
        /* Load up apples data */
        if (data.apples) 
        {
            $.each(data.apples, function(i,item) { 
                    var apple = new Apple(item.lat, item.lng, item.id)
            });
        }
    
        /* Start the update sequence */
        game_update();
    }
 
    function init_position(lat, lng) {
 
        /* Got location */
        user_print('You are at: ' + lat + ' : ' + lng);
 
        lat_center = lat;
        lng_center = lng;
 
        $.getJSON("data/gameState.js", init_game);
    }
 
    function initialize() {
        $("#info").ajaxError(function(event, request, settings){
            errors += 1;
            user_print("Error requesting page " + settings.url);
        });
 
        get_location(init_position);
    }
 
    $(document).ready(function() {
        dbg_print('MAIN: Start page init..');
        initialize();
    });
 
</script> 

    <link href="css/Map.css" rel="stylesheet" type="text/css" />
    </head> 
    
    <body> 
        <div id="dbg"></div> 
        <div id="info"></div> 
        <div id="map_canvas" style="width:100%; height:100%"></div> 
    </body> 
</html> 
 
 